package com.danke.lib.banner.widget.helper;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.Build;
import android.view.View;

/**
 * 设置圆角，https://github.com/GcsSloop/rclayout
 *
 * @author wupuquan
 * @version 1.0
 * @since 2020/3/19 13:57
 */
public class BannerRoundCornerHelper {

    public float[] radii = new float[8];   // top-left, top-right, bottom-right, bottom-left
    public Path clipPath;                 // 剪裁区域路径
    public Paint paint;                   // 画笔
    public RectF layer;                   // 画布图层大小

    public BannerRoundCornerHelper() {
        layer = new RectF();
        clipPath = new Path();
        paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
    }

    public void setRoundCorner(float roundCornerTopLeft, float roundCornerTopRight, float roundCornerBottomLeft, float roundCornerBottomRight) {
        radii[0] = roundCornerTopLeft;
        radii[1] = roundCornerTopLeft;

        radii[2] = roundCornerTopRight;
        radii[3] = roundCornerTopRight;

        radii[4] = roundCornerBottomRight;
        radii[5] = roundCornerBottomRight;

        radii[6] = roundCornerBottomLeft;
        radii[7] = roundCornerBottomLeft;
    }

    public boolean hasCorner() {
        for (float item : radii) {
            if (item > 0) {
                return true;
            }
        }
        return false;
    }

    public void onSizeChanged(View view, int w, int h) {
        layer.set(0, 0, w, h);
        refreshRegion(view);
    }

    public void refreshRegion(View view) {
        int w = (int) layer.width();
        int h = (int) layer.height();
        RectF areas = new RectF();
        areas.left = view.getPaddingLeft();
        areas.top = view.getPaddingTop();
        areas.right = w - view.getPaddingRight();
        areas.bottom = h - view.getPaddingBottom();
        clipPath.reset();
        clipPath.addRoundRect(areas, radii, Path.Direction.CW);
    }

    public void onClipDraw(Canvas canvas) {
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL);

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) {
            // https://blog.csdn.net/harvic880925/article/details/51288006
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
            canvas.drawPath(clipPath, paint);
        } else {
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));

            final Path path = new Path();
            path.addRect(0, 0, (int) layer.width(), (int) layer.height(), Path.Direction.CW);
            path.op(clipPath, Path.Op.DIFFERENCE); // https://www.jianshu.com/p/17fb1b542b39
            canvas.drawPath(path, paint);
        }
    }
}
